package com.may.controller;

import com.may.entity.User;
import com.may.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author mayuanbao
 * @date 2020-11-04 20:24
 */
@Slf4j
@Controller
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/login")
    public String login(String name, String password) {
        // 获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(name, password));
            return "index";
        } catch (UnknownAccountException e) {
            log.warn("用户名错误");
        } catch (IncorrectCredentialsException e) {
            log.warn("密码错误");
        }
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequestMapping("/toRegister")
    public String toRegister() {

        return "register";
    }

    @RequestMapping("/register")
    public String register(User user) {
        // uuid作为盐值进行MD5加密，并hash散列1024次
        String salt = UUID.randomUUID().toString().replace("-", "");
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        userService.save(user);
        return "redirect:/login";

    }
}
